package receiver;

import java.util.Calendar;
import Config.setting;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ScheduleReceiver  extends BroadcastReceiver {
	  // Restart service every xx seconds
	  private static final long REPEAT_TIME = setting.getRefreshServiceTime();
	  @Override
	  public void onReceive(Context context, Intent intent) {
		  	Log.d("MyScheduleReceiver", "onreceice");
			AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
			Intent i = new Intent(context, StartServiceReceiver.class);
			PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);
			Calendar cal = Calendar.getInstance();
	/*		// Start 30 seconds after boot completed
			cal.add(Calendar.SECOND, 0);
	*/		if(intent.getExtras().getBoolean("start")){
				//start service instance
				Log.d("tag", "start SV");
				// Fetch every repeat_time seconds
				// InexactRepeating allows Android to optimize the energy consumption
				service.setInexactRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), REPEAT_TIME, pending);
				// service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
				// REPEAT_TIME, pending);
			} else{
				//stop current sfervice
				Log.d("tag", "stop SV");
				service.cancel(pending);
			}
	  	}
} 